package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;

public class CompressProtocol implements Runnable {
	public static final int BUFSIZE = 1024;// size of receive buffer
	private Socket clntSock;
	private Logger logger;

	public CompressProtocol(Socket clntSock, Logger logger) {
		this.clntSock = clntSock;
		this.logger = logger;
	}
	/**
	 * Given a socket connected to the compression client,read the uncompressed bytes
	 * from the client and write the compressed bytes back
	 * @param clntSock
	 * @param logger
	 */
	public static void handleCompressClient(Socket clntSock, Logger logger) {
		try {
			// get the input and output streams from socket
			InputStream in = clntSock.getInputStream();
			GZIPOutputStream out = new GZIPOutputStream(
					clntSock.getOutputStream());
			byte[] buffer = new byte[BUFSIZE];// allocate read/write buffer
			int bytesRead; // number of bytes read
			// receive until client closes connection, indicated by -1 return
			while ((bytesRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesRead);
			}
			out.finish();// flush bytes from GZIPOutputstream
			logger.info("Client " + clntSock.getRemoteSocketAddress()
					+ " finished");
		} catch (IOException e) {
			logger.log(Level.WARNING, "Exception in echo protocol", e);
		}

		try {// close socket
			clntSock.close();
		} catch (IOException e) {
			logger.info("Exception= " + e.getMessage());
		}
	}

	@Override
	public void run() {
		handleCompressClient(clntSock, logger);	

	}

}
